<template>
  <el-card>
    <el-row>
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="danger" style="margin-right: 10px" @click="handleBulkDelete">批量删除</el-button>
    </el-row>
    <el-table
        v-loading="data.loading === true"
        :data="data.tableData"
        style="width: 100%; margin-top: 10px; overflow: hidden"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" sortable ></el-table-column>
      <el-table-column prop="id" label="序号" sortable min-width="200"></el-table-column>
      <el-table-column prop="title" label="分类名称" sortable min-width="500"></el-table-column>
      <el-table-column label="操作" min-width="100">
        <template #default="scope">
          <el-button-group>
            <el-button size="default" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="default" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="data.total" style="margin-top: 10px">
      <el-pagination
          background
          small
          :page-size="data.pageSize"
          :current-page="data.pageNum"
          layout="total,prev, pager, next,jumper"
          :total="data.total"
          @current-change="handleCurrentChange"
      ></el-pagination>
    </div>


<!--    弹窗-->
    <el-dialog v-model="data.formVisible" title="分类信息" width="30%" destroy-on-close>
      <el-form :model="data.form" label-width="120px" ref="ruleFormRef" :rules="data.rules">
        <el-col :span="20">
          <el-form-item label="分类名称" prop="title">
            <el-input v-model="data.form.title" placeholder="请输入"/>
          </el-form-item>
        </el-col>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="Formcancel">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>



<script setup>

import {onMounted, reactive, ref} from "vue";
import {createApi, deleteApi, listApi, updateApi} from "@/api/classification";
import {ElMessage, ElMessageBox} from "element-plus";

const data=reactive({
  tableData:[],
  loading:false,
  formVisible:false,
  total:0,
  pageNum:1,
  pageSize:10,
  form:{
    id:'',
    title:'',
  },
  rules:{
    title: [{ required : true, message : '请输入分类名', trigger : 'blur'}]
  }
})

onMounted(()=>{
  getDataList();

})
const getDataList=()=>{
  data.loading=true;
  setTimeout(() => {
    data.loading = false;
  }, 1000);
  listApi({
    pageNum:data.pageNum,
    pageSize:data.pageSize,
  }).then(res=>{
    // console.log(res);
    data.tableData=res.data.list;
    data.total=res.data.total;
    data.pageNum=res.data.pageNum;
    data.pageSize=res.data.pageSize;
  }).catch(err=>{
    console.log(err);
  })
}
const handleAdd=()=>{

  data.formVisible=true;
}
const Formcancel=()=>{
  data.form={};
  data.formVisible=false;
}
const ruleFormRef = ref()
const save=async () => {
  try {
    //验证表单
    const isValid = await ruleFormRef.value.validate();
    if (!isValid) {
      return;
    }

    if (data.form.id) {
      updateApi(data.form).then(res => {
        // console.log(res)
        if (res.code === 200) {
          ElMessage.success(res.msg);
          Formcancel();
          getDataList();
        } else {
          ElMessage.error(res.msg);
        }
      })
    } else {
      createApi(data.form).then(res => {
        // console.log(res)
        if (res.code === 200) {
          ElMessage.success(res.msg);
          Formcancel();
          getDataList();
        } else {
          ElMessage.error(res.msg);
        }
      })
    }
  } catch (err) {
    console.error(err);
  }
}

const handleEdit = (row) => {
  data.form=row;
  data.formVisible=true;
}

const handleDelete = (row) => {
  ElMessageBox.confirm('删除后数据无法恢复，确认删除？','警告',{type:'warning'})
      .then(()=>{
        deleteApi({'ids':row.id}).then(res=>{
          if (res.code===200){
            ElMessage.success('删除成功')
            getDataList();
          }else {
            ElMessage.error(res.msg)
          }
        })
      }).catch(err=>{
        console.error('请求错误',err);
        ElMessage.info('取消');
  })
}
const handleSelectionChange=(selection)=>{
  data.selectedIds = selection.map(item => item.id);
}
const handleBulkDelete = () => {
  if (data.selectedIds===undefined||data.selectedIds.length===0){
    ElMessage.warning('请选择要删除的分类')
    return;
  }
  // 将数组转换为逗号分隔的字符串
  const idsParam = data.selectedIds.join(',');
  ElMessageBox.confirm('确认删除选中的标签吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(()=>{
    deleteApi({'ids':idsParam}).then(res=>{
      if (res.code===200){
        ElMessage.success(res.msg);
        getDataList();
      }else {
        ElMessage.error(res.msg);
      }
    }).catch(err=>{
      console.error(err);
    })
  })
}
const handleCurrentChange = (number) => {
  data.pageNum=number;
  getDataList();
}
</script>
<style scoped>

</style>